# @Time    : 2020/2/18 14:27
# @Author  : wumao
# @Email   : kanhebei@dingtalk.com

from . import home_bp
from .helper.func import view
from ...models import Article, Body
from ...extends.flask_sqlalchemy import db
from .form import EditForm
from flask import flash, redirect, url_for


@home_bp.route('/archive/<int:article_id>.html')
def article_select(article_id):
    article = Article.query.filter_by(id=article_id, status=1).first_or_404()
    article.hot_plus()
    newest = Article.query.filter_by(status=1).order_by(Article.id.desc())
    top = newest.filter_by(top=1)
    good = newest.filter_by(good=1)
    hot = newest.filter_by(hot=1)
    return view(
        'article.html',
        article=article,
        good=good,
        hot=hot,
        newest=newest,
        top=top
    )


@home_bp.route('/publish/', methods=['GET', 'POST'])
def publish():
    form = EditForm()
    if form.validate_on_submit():
        with db.auto_commit():
            article = Article()
            article.title = form.title.data
            article.category_id = form.category_id.data
            article.author = form.author.data
            article.status = False
            article.body = Body(content=form.content.data)
            article.remark = '{}/{}'.format(form.address.data, form.phone.data)
            article.is_member = True
            db.session.add(article)
        flash('操作成功！工作人员会在1-3个工作日进行审核', 'success')
        return redirect(url_for('home.publish'))
    return view('publish.html', form=form)